package com.jhd.fuzhou.view.special;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.IllegalRecordDtlVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SearchUnit;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class SpecialCheckContentActivity extends BaseActivity {
    @BindView(R.id.iv_cancel)
    ImageView iv_cancel;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.btn_confirm)
    Button btn_confirm;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_loading)
    TextView tv_loading;
    private Context context= this;
    private List<IllegalRecordDtlVo> illegalRecordDtlVoList =new ArrayList<>();
    private SearchUnit searchUnit=new SearchUnit();
    private EnforceBasisAdapter enforceBasisAdapter;
    private LinearLayoutManager layoutManager;
    int checkPosition=-1;
    private String code;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_check_content);
    }

    @Override
    protected void processLogic() {
        code=getIntent().getStringExtra("code");
        layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    tv_loading.setText(getString(R.string.loading));
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    searchUnit.setKeyword(searchUnit.getKeyword());
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                         getEnforceBasisList();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);
                }
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);
        searchUnit.setKeyword(et_search.getText().toString());
        getEnforceBasisList();
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search.getText().toString());
                illegalRecordDtlVoList.clear();
                getEnforceBasisList();
                return false;
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchUnit.setPageIndex(1);
                    searchUnit.setKeyword(s.toString());
                    illegalRecordDtlVoList.clear();
                    getEnforceBasisList();
                    iv_cancel.setVisibility(View.GONE);
                }else{
                    iv_cancel.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    @OnClick({R.id.iv_cancel,R.id.btn_confirm})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.iv_cancel://点击清空输入框，并隐藏取消按钮
                et_search.setText("");
                iv_cancel.setVisibility(View.GONE);
                break;
            case R.id.btn_confirm:
                if(checkPosition!=-1){
                    Intent intent=new Intent(context, SpecialStandardWordActivity.class);
                    Gson gson = new Gson();
                    intent.putExtra("enforceBasis",gson.toJson (illegalRecordDtlVoList.get(checkPosition)));
                    startActivity(intent);
                    finish();
                }else{
                    CustomToast.showText(context,"请选择一个违法行为!",3000,0,0).show();
                }
                break;
        }
    }

    public void getEnforceBasisList(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params =  new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize",20);/*
        if(!StringUtil.isNullOrEmpty(code))params.put("code", code);
        params.put("specialityCategory",(supervisionInspectionVo.getSpecialityCategory()==null)?"": supervisionInspectionVo.getSpecialityCategory());*/
        if(!StringUtil.isNullOrEmpty(code)){
            params.put("code", code);
        }else{
            params.put("specialityCategory",(supervisionInspectionVo.getSpecialityCategory()==null)?"": supervisionInspectionVo.getSpecialityCategory());
        }
        params.put("status","1");
        params.put("keyword",et_search.getText().toString());//模糊查询
        //状态(0-禁用 1-启用 2-删除)
        Call<JsonForResult> jsonForResultCall = vs.getEnforceBasisList(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        tv_loading.setVisibility(View.GONE);
                        if (jsonForResult.getData() != null) {
                            List<IllegalRecordDtlVo> enforceBasisses = JSON.parseArray(jsonForResult.getData().toString(), IllegalRecordDtlVo.class);
                            for (IllegalRecordDtlVo illegalRecordDtlVo : enforceBasisses) {
                                illegalRecordDtlVoList.add(illegalRecordDtlVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                enforceBasisAdapter =new EnforceBasisAdapter(illegalRecordDtlVoList);
                                recyclerView.setAdapter(enforceBasisAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                enforceBasisAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            enforceBasisAdapter =new EnforceBasisAdapter(illegalRecordDtlVoList);
                            recyclerView.setAdapter(enforceBasisAdapter);
                            tv_loading.setText("我是有底线的！");
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                String msg = "获取违法行为失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }


    public class EnforceBasisAdapter extends RecyclerView.Adapter<EnforceBasisAdapter.ViewHolder> {
        private List<IllegalRecordDtlVo> illegalRecordDtlVoList;

        public EnforceBasisAdapter(List<IllegalRecordDtlVo> illegalRecordDtlVoList) {
            this.illegalRecordDtlVoList = illegalRecordDtlVoList;
        }

        @NonNull
        @Override
        public EnforceBasisAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_enforce_basis, parent, false);
            EnforceBasisAdapter.ViewHolder viewHolder = new EnforceBasisAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull EnforceBasisAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(illegalRecordDtlVoList.get(position).getContent());
            if(!"1".equals(illegalRecordDtlVoList.get(position).getEnd())){
                holder.rb_radio.setClickable(false);
                holder.rb_radio.setButtonDrawable(null);
                System.out.println("位置1："+position);
            }else{
                holder.rb_radio.setClickable(true);
                holder.rb_radio.setButtonDrawable(R.drawable.selector_radiobutton);
            }
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!"1".equals(illegalRecordDtlVoList.get(position).getEnd())){
                        checkPosition=-1;
                    }else{
                        checkPosition=position;
                    }
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return illegalRecordDtlVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }
}